// 购物车页面
const app = getApp()

Page({
  data: {
    cartItems: [],
    totalPrice: 0,
    deliveryFee: 5,
    finalPrice: 0
  },

  onLoad() {
    this.loadCartData()
  },

  onShow() {
    this.loadCartData()
  },

  // 加载购物车数据
  loadCartData() {
    const cartItems = app.globalData.cart
    const totalPrice = app.getCartTotal()
    
    this.setData({
      cartItems,
      totalPrice,
      finalPrice: totalPrice + this.data.deliveryFee
    })
    
    console.log('购物车数据:', cartItems)
  },

  // 增加商品数量
  increaseQuantity(e) {
    const { productId, storeId } = e.currentTarget.dataset
    const item = this.data.cartItems.find(item => 
      item.productId === parseInt(productId) && item.storeId === parseInt(storeId)
    )
    
    if (item) {
      app.addToCart({
        id: item.productId,
        name: item.name,
        price: item.price,
        imageUrl: item.image
      }, item.storeId)
      
      this.loadCartData()
    }
  },

  // 减少商品数量
  decreaseQuantity(e) {
    const { productId, storeId } = e.currentTarget.dataset
    app.removeFromCart(parseInt(productId), parseInt(storeId))
    this.loadCartData()
  },

  // 移除商品
  removeItem(e) {
    const { productId, storeId } = e.currentTarget.dataset
    app.removeProductFromCart(parseInt(productId), parseInt(storeId))
    this.loadCartData()
    
    wx.showToast({
      title: '已移除商品',
      icon: 'success'
    })
  },

  // 继续购物
  goToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 去结算
  goToCheckout() {
    if (this.data.cartItems.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      })
      return
    }

    // 获取第一个商品的店铺信息
    const firstItem = this.data.cartItems[0]
    if (!firstItem) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      })
      return
    }

    const storeId = firstItem.storeId
    const storeName = encodeURIComponent('美食店铺')
    
    wx.navigateTo({
      url: `/pages/order/order?storeId=${storeId}&storeName=${storeName}&orderType=delivery`
    })
  }
}) 